//
//  StatusCell.swift
//  LBWeibo
//
//  Created by 李博 on 15/6/30.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

protocol StatusCellDelegate: NSObjectProtocol {
    ///选中配图图片代理方法
    func statusCellDidSelectPhoto(cell: StatusCell, photoIndex: Int)
}

///配图视图可重用标示符
private let LBPictureCellReuseIdentifier = "LBPictureCellReuseIdentifier"

class StatusCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
    
    ///配图视图宽度约束
    private var widthCons: NSLayoutConstraint?
    ///配图视图高度约束
    private var heightCons: NSLayoutConstraint?
    /// 配图视图顶部约束
    private var topCons: NSLayoutConstraint?
    
    weak var photoDelegate: StatusCellDelegate?
    
    ///转发标签
    var forwardLabel = UILabel()
    
    ///微博数据模型
    var status: Status? {
        didSet {
            
            //转发文字
            let forwardText = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            forwardLabel.attributedText = EmoticonPackage.emoticonAttributeString(forwardText, font: forwardLabel.font)
            
            //设置头像
            iconView.sd_setImageWithURL(status?.user?.profileUrl)
            
            //设置认证图标
            vipIconView.image = status?.user?.verifiedImage
            //设置会员图标
            memberIconView.image = status?.user?.mbrankImage
            
            nameLabel.text = status?.user?.name
            //发布微博时间
            timeLabel.text = NSDate.sinaDateWithString(status?.created_at ?? "").dateDescription()
            
            sourceLabel.text = status?.source
            contentLabel.attributedText = EmoticonPackage.emoticonAttributeString(status?.text ?? "", font: contentLabel.font)
           
            let result = calcPicViewSize(status!)
            //设置配图长宽约束
            topCons?.constant = result.viewSize.height == 0 ? 0 : 12
            widthCons?.constant = result.viewSize.width
            heightCons?.constant = result.viewSize.height
            
            pictureLayout.itemSize = result.itemSize
            
            //刷新图片视图
            pictureView.reloadData()
        }
    }
    
    ///cell 的可重用表示符
    class  func cellIdentifier(status: Status) -> String {
        return status.retweeted_status != nil ? LBStatusForwardCellIdentifier : LBStatusNormalCellIdentifier
    }
    
    
    ///计算行高
    func rowHeight(status: Status) -> CGFloat {
        self.status = status
        
        //更新布局
        layoutIfNeeded()
        
        //返回行高
        return CGRectGetMaxY(footerView.frame)
    }
    
    ///记录配图视图的约束
    func recordPictureViewCons(cons: [NSLayoutConstraint]) {
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        widthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        heightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    // MARK: - 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LBPictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
        cell.imageURL = status!.pictureURLs![indexPath.item]
        
        return cell
    }
    
    ///  返回大图对应的全屏之后的屏幕位置
    func fullScreenFrame(photoIndex: Int) -> CGRect {
        
        //取得已缓存图片
        let urlString = status!.pictureURLs![photoIndex].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
        // 1. 计算比例
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        
        let w = screenSize.width
        let h = w * scale
        var y: CGFloat = 0
        
        if h < screenSize.height {
            y = (screenSize.height - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)

    }
    
    ///取得指定图片索引的屏幕Frame
    func pictureCellScreenFrame(pictureIndex: Int) -> CGRect {
        let indexPath = NSIndexPath(forItem: pictureIndex, inSection: 0)
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        return pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }

    
    ///选中配图图片代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //预先加载大图
        let url = status!.largePicURLs![indexPath.item]
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        
        //测试
//        let v = UIView(frame: fullScreenFrame(indexPath.item))
//        v.backgroundColor = UIColor.redColor()
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (bytes, totalBytes) -> Void in
            
            //设置进度
            let progress = CGFloat(bytes) / CGFloat(totalBytes)
          
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                cell.iconView.progress = progress
            })
            
            }) { [unowned self] (_, error, _, _, _) -> Void in
                print(error)
                
                // 大图缓存结束后，再执行回调
                
                self.photoDelegate?.statusCellDidSelectPhoto(self, photoIndex: indexPath.item)
        }
        
    
    }
    
    
    ///  根据微博模型计算图片是的大小
    ///返回多个数值，在 OC 中指针的指针，在 swift 中是：元组，参数，可以直接在返回结果用 . 语法访问
    private func calcPicViewSize(status: Status) -> (viewSize: CGSize, itemSize: CGSize) {
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        //获取图片数量
        let count = status.pictureURLs?.count ?? 0
        //没有图片
        if count == 0 {
            return (CGSizeZero,itemSize)
        }
        //单图
        if count == 1 {
            let key = status.pictureURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            return (image.size, image.size)
        }
        
        //4张图片
        if count == 4 {
            let w = itemSize.width * 2 + margin
            return (CGSize(width: w, height: w),itemSize)
        }
        
        //多张图片
        ///每行图片数量
        let rowCount = 3
        
        let row = (count - 1) / rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemSize.height * CGFloat(row) + CGFloat(row - 1) * margin
        
        return (CGSize(width: w, height: h), itemSize)
        
        
    }

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        // 屏幕宽度
        let screenWidth = UIScreen.mainScreen().bounds.width
        //顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.7, alpha: 1.0)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWidth, height: 10))
        
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(timeLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        addSubview(pictureView)
        addSubview(footerView)
        footerView.backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        // 准备配图视图
        preparePictureView()
        
        // 头像
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: 34, height: 34), offset: CGPoint(x: 12, y: 22))
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPoint(x: 12, y: 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 8, y: 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: 12, y: 0))
      contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))

        // 页脚视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWidth, height: 44), offset: CGPoint(x: -12, y: 12))
        
    
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///准备配图视图
    private func preparePictureView() {
        
        //设置背景图片
        pictureView.backgroundColor = UIColor.lightGrayColor()
        //设置数据源
        pictureView.dataSource = self
        pictureView.delegate = self
        //注册可重用cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: LBPictureCellReuseIdentifier)
        //设置layout
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
        
    }
    
    
    
    //MARK: -控件的懒加载
    lazy var iconView = UIImageView()
    lazy var nameLabel = UILabel(color: UIColor.orangeColor(), fontSize: 14)
    lazy var timeLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    
    lazy var memberIconView: UIImageView = UIImageView()
    lazy var vipIconView: UIImageView = UIImageView()
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
    lazy var contentLabel: KILabel = KILabel(textColor: UIColor.darkGrayColor(), fontSize: 15, layoutWidth: UIScreen.mainScreen().bounds.width - 16)
    
    //图像视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    //页脚视图
    lazy var footerView: StatusFooterView = StatusFooterView()
    
}
// 配图cell
private class StatusPictureCell:UICollectionViewCell {
    
    //图像地址
    var imageURL: NSURL? {
        didSet {
            iconView.progress = 0
            
            //如果本地有缓存，直接加载本地缓存，如果没有，直接下载
            iconView.sd_setImageWithURL(imageURL)
            
            gifIconView.hidden = !(imageURL!.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置图片填充模式----等比例填充，需要裁切
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        //两句配合使用
        iconView.clipsToBounds = true
        
        addSubview(iconView)
        //与cell大小完全一致
        iconView.ff_Fill(self)
        
        addSubview(gifIconView)
        gifIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
        
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private lazy var iconView: LBImageView = LBImageView()
    private lazy var gifIconView: UIImageView = {
        let gifIV = UIImageView(image: UIImage(named: "timeline_image_gif"))
        gifIV.hidden = true
        return gifIV
    }()

}

///页脚视图
class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(forwardBtn)
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        //布局 水平布局
        ff_HorizontalTile([forwardBtn,commentBtn,likeBtn], insets: UIEdgeInsetsZero)
        
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var forwardBtn: UIButton = UIButton(title: "转发", imageName: "timeline_icon_retweet", fontSize: 12, titleColor: UIColor.darkGrayColor())
    
    lazy var commentBtn: UIButton = UIButton(title: "评论", imageName: "timeline_icon_comment", fontSize: 12, titleColor: UIColor.darkGrayColor())
    
    lazy var likeBtn: UIButton = UIButton(title: "点赞", imageName: "timeline_icon_unlike", fontSize: 12, titleColor: UIColor.darkGrayColor())
    
    
    
}




